import Blockly from 'blockly/core'
import 'blockly/python_compressed'
import 'blockly/blockly_compressed'
import 'blockly/blocks_compressed'

// range函数模块的定义
Blockly.Blocks.range_function = {
  init: function () {
    // range模块需要插入另外两个返回值为Number类型的模块
    this.appendValueInput('upperRange')
      .setCheck('Number')
      .setAlign(Blockly.ALIGN_CENTRE)
      .appendField('range')
    this.appendValueInput('lowerRange').setCheck('Number').appendField('to')
    this.setInputsInline(true)
    this.setOutput(true, null)
    this.setColour(230)
    this.setTooltip('输入范围的边界，默认为0到10的范围')
    this.setHelpUrl('')
  }
}

// 代码格式：range(upperRange, lowerRange)
Blockly.Python.range_function = function (block) {
  let upperRange = Blockly.Python.valueToCode(
    block,
    'upperRange',
    Blockly.Python.ORDER_NONE
  )
  let lowerRange = Blockly.Python.valueToCode(
    block,
    'lowerRange',
    Blockly.Python.ORDER_NONE
  )
  const regularExpressionForNumbers = /^\d+$/
  if (regularExpressionForNumbers.test(lowerRange) && upperRange === '') {
    const num = parseInt(lowerRange) - 10
    upperRange = num.toString()
  } else if (
    regularExpressionForNumbers.test(upperRange) &&
    lowerRange === ''
  ) {
    const num = parseInt(upperRange) + 10
    lowerRange = num.toString()
  }
  if (upperRange === '') {
    upperRange = '0'
  }
  if (lowerRange === '') {
    lowerRange = '10'
  }
  if (
    regularExpressionForNumbers.test(upperRange) &&
    regularExpressionForNumbers.test(lowerRange) &&
    parseInt(upperRange) >= parseInt(lowerRange)
  ) {
    const num = parseInt(upperRange) + 10
    lowerRange = num.toString()
  }
  const code = 'range(' + upperRange + ', ' + lowerRange + ')'
  return [code, Blockly.Python.ORDER_NONE]
}

export default Blockly
